package servlet;

import dao.DaoFactory;
import entity.MyFile;
import entity.Student;
import utils.PageInfo;
import utils.PathUtils;
import org.apache.commons.lang3.StringUtils;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

import java.sql.SQLException;

@WebServlet("/myfile")
public class FileServlet extends HttpServlet {



    private static final long serialVersionUID = -8014761719195353369L;

    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        doPost(req, resp);
    }

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        String method = req.getParameter("method");
        if ("delete".equals(method)) {
            this.delete(req, resp);
        } else if ("list".equals(method)) {
            this.list(req, resp);
        }
    }

    private void delete(HttpServletRequest req, HttpServletResponse resp) {
        Integer f_id = getIntParameter(req,"f_id");
        try {
            DaoFactory.getInstance().getFileDao().delete(f_id);
            resp.sendRedirect(PathUtils.getBasePath(req) + "myfile?method=list&msg=文件删除成功!");
        } catch (SQLException throwables) {
            throwables.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }

    }

    private void list(HttpServletRequest req, HttpServletResponse resp) {
        Integer pageNo = getIntParameter(req,"pageNo");
        String f_name = req.getParameter("f_name");
        String msg = req.getParameter("msg");
        Student student = (Student)req.getSession().getAttribute("user");
        String s_id = student.getS_id();

        MyFile myFile = new MyFile();
        myFile.setF_name(f_name);
        PageInfo<MyFile> pageInfo = new PageInfo<>(pageNo);
        try {
            pageInfo = DaoFactory.getInstance().getFileDao().listFile(s_id, f_name, pageInfo);
            req.setAttribute("pageInfo", pageInfo);
            req.setAttribute("file",myFile);
            //回写到页面
            req.getRequestDispatcher("page/Student/mycloud.jsp?msg="+msg).forward(req, resp);
        } catch (Exception e) {
            e.printStackTrace();
        }

    }

    public Integer getIntParameter(HttpServletRequest request,String name) {
        if(StringUtils.isNoneBlank(request.getParameter(name))) {
            return Integer.parseInt(request.getParameter(name));
        }else {
            return null;
        }
    }
}
